<template>
	<view style="display: flex;flex-direction: column;width: 100vw;height: 100vh;background-color: #f5f5f5;">
		<view
			style="display: flex;flex-direction: row;background-color: #ffffff;align-items: center;width: 100%;padding-top: 10px;padding-bottom: 10px;padding-top: 40px;">
			<view
				style="display: flex;width: 100%;flex-direction: row;align-items: center;justify-content: space-evenly;">
				<text style="">路线录制</text>
				<view
					style="padding: 6px;display: flex;border-radius: 20px;background-color: #ffffff;align-items: center;margin: 2px;border: 1px #eaeaea solid;width: 60%;">
					<picker mode="selector" :range="droneIdList" @change="handlecurrentSelectDroneIdChange"
						style="display: flex;justify-content: center;align-items: center;width: 100%;">
						<view v-if="hasChooseDrone">{{ '无人机id：' + currentSelectDroneId}}</view>
						<view v-if="!hasChooseDrone">{{'请选择无人机' }}</view>
					</picker>
				</view>
			</view>

			<image src="/static/icons/return_5_black.png" mode="aspectFill"
				style="width: 20px;height: 20px;margin-right: 6px" @click="navigateToRouteController"></image>
		</view>


		<view v-if="telemetryData!=null" style="width: 100%;height:100%">
			<!-- 地图容器 -->
			<map id="myMap" :key="mapKey" :latitude="telemetry_GPS_to_Gcj02[1]"
				:longitude="telemetry_GPS_to_Gcj02[0]" :markers="markers" :scale="21"
				style="width: 100%;height: 100%;">
			</map>
		</view>
		<!-- 数据面板 -->
		<view
			style="height: 100px;margin: 2px ;display: flex;  flex-direction: row; justify-content: start;flex-wrap: wrap;font-size: 12px;background-color: #ffffff;border-radius: 10px;border:1px solid #bfbfbf">
			<view
				style="width: 50%;display: flex;justify-content: center;align-items: center;padding-bottom: 6px;padding-top: 6px;">
				<image src="/static/icons/speed.png" mode="aspectFill"
					style="width: 16px;height: 16px;margin-right: 2px;"></image>
				速度{{telemetryData.current_speed}}米每秒
			</view>
			<view
				style="width: 50%;display: flex;justify-content: center;align-items: center;padding-bottom: 6px;padding-top: 6px;">
				<image src="/static/icons/expand-height-line.png" mode="aspectFill"
					style="width: 16px;height: 16px;margin-right: 2px;"></image>高度{{telemetryData.altitude}}米
			</view>
			<view style="width: 50%;display: flex;justify-content: center;padding-bottom: 6px;">
				<image src="/static/icons/load.png" mode="aspectFill"
					style="width: 16px;height: 16px;margin-right: 2px;"></image>
				cpu负载{{telemetryData.system_usage}}%
			</view>
			<view style="width: 50%;display: flex;justify-content: center;padding-bottom: 6px;">
				<image src="/static/icons/locate.png" mode="aspectFill"
					style="width: 16px;height: 16px;margin-right: 2px;"></image>
				已记录点{{recordingPoints.length}}
			</view>
		</view>
		<!-- 路线录制按钮 -->
		<view
			style="margin: 2px;display: flex;flex-direction: row;background-color: #ffffff;border-radius: 10px;border:1px solid #bfbfbf;padding: 4px;justify-content: space-evenly; ">
			<view style="padding: 6px; display: flex;align-items: center;" @click="startRecording">
				<image :src="isRecording ? '/static/icons/record_red.png' : '/static/icons/record_black.png'"
					mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
				<view :style="{ fontSize: '14px', color: isRecording ? '#ff0000' : '#000000' }">开始录制</view>
			</view>

			<view style="padding: 6px; display: flex;align-items: center;" @click="handleCancelRecording">
				<image src="/static/icons/cancel_2_black.png" mode="aspectFill"
					style="height: 20px; width: 20px; margin-right: 4px;" />
				<view :style="{ fontSize: '14px', color: '#000000' }">取消录制</view>
			</view>

			<view style="padding: 6px; display: flex;align-items: center;" @click="handleSaveRecording">
				<image src="/static/icons/save_black.png" mode="aspectFill"
					style="height: 20px; width: 20px; margin-right: 4px;" />
				<view :style="{ fontSize: '14px', color : '#000000' }">保存录制</view>
			</view>
		</view>
		<!-- 无人机操作按钮 -->
		<view
			style="margin: 2px;display: flex;flex-direction: row;height: 400px;background-color: #ffffff;border-radius: 10px;border:1px solid #bfbfbf;padding: 4px;">

			<view
				style="display: flex;  flex-direction: column; justify-content: space-evenly;color: #eaeaea;border-right: #acacac 1px solid;align-items: center;">
				<view style="padding: 6px; display: flex; align-items: center; " @click="sendTakeOffOrder">
					<image
						:src="isSendTakeOffOrder ? '/static/icons/take_off_red.png' : '/static/icons/take_off_black.png'"
						mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
					<view :style="{ fontSize: '14px', color: isSendTakeOffOrder ? '#ff0000' : '#000000' }">起飞</view>
				</view>
				<view style="width: 70px;"></view>
				<view style="padding: 6px; display: flex;align-items: center;" @click="sendLandOrder">
					<image :src="isSendTakeOffOrder ? '/static/icons/land_black.png' : '/static/icons/land_red.png'"
						mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
					<view :style="{ fontSize: '14px', color: isSendTakeOffOrder ? '#000000' : '#ff0000' }">降落</view>
				</view>
			</view>
			<view style="display: flex;flex-direction: column;padding: 2px;width:100%;height:100%">
				<view
					style="display: flex;flex-direction: row;width: 100%;height:  25%;justify-content: space-evenly;border-bottom: 1px #acacac solid;">
					<view
						style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;border-right:1px #acacac solid ;"
						@click="handleAutoMode">
						<image :src="isAutoMode ? '/static/icons/auto_red.png' : '/static/icons/auto_black.png'"
							mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
						<view :style="{ fontSize: '14px', color: isAutoMode ? '#ff0000' : '#000000' }">自动</view>
					</view>

					<view
						style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;border-right:1px #acacac solid ;"
						@click="handleDelete">
						<image src="/static/icons/delete_red.png" mode="aspectFill"
							style="height: 20px; width: 20px; margin-right: 4px;" />
						<view :style="{ fontSize: '14px', color: '#000000' }">删除</view>
					</view>

					<view style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;"
						@click="handleAdd">
						<image src="/static/icons/add.png" mode="aspectFill"
							style="height: 16px; width: 16px; margin-right: 4px;" />
						<view :style="{ fontSize: '14px', color : '#000000' }">新增</view>
					</view>
				</view>
				<view
					style="display: flex;flex-direction: row;width: 100%;height: 25%;justify-content: space-evenly;border-bottom: 1px #acacac solid;">
					<view
						style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;border-right:1px #acacac solid ;"
						@click="handleActionClick('left')">
						<image
							:src="currentAction === 'left' ? '/static/icons/turn-left_red.png' : '/static/icons/turn-left.png'"
							mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
						<view :style="{ fontSize: '14px', color: currentAction === 'left' ? '#ff0000' : '#000000' }">左转
						</view>
					</view>

					<view
						style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;border-right:1px #acacac solid ;"
						@click="handleActionClick('forward')">
						<image
							:src="currentAction === 'forward' ? '/static/icons/forward_red.png' : '/static/icons/forward.png'"
							mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
						<view :style="{ fontSize: '14px', color: currentAction === 'forward' ? '#ff0000' : '#000000' }">
							前进</view>
					</view>

					<view style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;"
						@click="handleActionClick('right')">
						<image
							:src="currentAction === 'right' ? '/static/icons/turn-right_red.png' : '/static/icons/turn-right.png'"
							mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
						<view :style="{ fontSize: '14px', color : currentAction === 'right' ? '#ff0000' : '#000000' }">
							右转</view>
					</view>
				</view>

				<view
					style="display: flex;flex-direction: row;width: 100%;height: 25%;justify-content: space-evenly;border-bottom: 1px #acacac solid;">
					<view
						style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;border-right:1px #acacac solid ;"
						@click="handleActionClick('u_turn_left')">
						<image
							:src="currentAction === 'u_turn_left' ? '/static/icons/u-turn-left_red.png' : '/static/icons/u-turn-left.png'"
							mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
						<view
							:style="{ fontSize: '14px', color: currentAction === 'u_turn_left' ? '#ff0000' : '#000000' }">
							左掉头</view>
					</view>

					<view
						style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;border-right:1px #acacac solid ;"
						@click="handleActionClick('backward')">
						<image
							:src="currentAction === 'backward' ? '/static/icons/reverse_red.png' : '/static/icons/reverse.png'"
							mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
						<view
							:style="{ fontSize: '14px', color: currentAction === 'backward' ? '#ff0000' : '#000000' }">
							后退</view>
					</view>

					<view style=" display: flex;align-items: center;justify-content: center;height: 100%;width: 33%;"
						@click="handleActionClick('u_turn_right')">
						<image
							:src="currentAction === 'u_turn_right' ? '/static/icons/u-turn-right_red.png' : '/static/icons/u-turn-right.png'"
							mode="aspectFill" style="height: 20px; width: 20px; margin-right: 4px;" />
						<view
							:style="{ fontSize: '14px', color : currentAction === 'u_turn_right' ? '#ff0000' : '#000000' }">
							右掉头</view>
					</view>
				</view>

				<view
					style="padding: 6px; display: flex; align-items: center;height: 25%;width: 100%;justify-content: center;"
					@click="handleActionClick('pause')">
					<image
						:src="currentAction === 'pause' ? '/static/icons/pause_red.png' : '/static/icons/pause_black.png'"
						mode="aspectFill" style="height: 28px; width: 28px; margin-right: 4px;" />
					<view :style="{ fontSize: '16px', color: currentAction === 'pause' ? '#ff0000' : '#000000' }">暂停
					</view>
				</view>
			</view>
		</view>

	</view>

</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted
	} from "vue";
	import PageLayout from "/pages/PageLayout/PageLayout.vue";
	import {
		navigateToRouteController,
		wgs84ToGcj02
	} from "/utils/Utils";
	import {
		sendSpeedCommand
	} from "/utils/HttpUtils";
	
	import { onShow, onHide } from '@dcloudio/uni-app';
	// 标记点数组（支持多个点）
	const markers = ref([]);

	let isSendTakeOffOrder = ref(false);

	const timer = ref(null);

	// 存储路线id和名称
	const routeNameAndId = ref([]);
	// 存储无人机ID列表
	const droneIdList = ref([]);
	//存储所选路线名称和id
	const currentSelectRouteNameAndId = ref({});
	//存储所选无人机id
	const currentSelectDroneId = ref();
	//存储是否选择无人机
	const hasChooseDrone = ref(false);
	//存储是否选择路线
	const hasChooseRoute = ref(false);
	//暂存无人机遥测数据
	const telemetryData = ref({
		"current_gps": {
			"latitude": 30.3096666,
			"longitude": 120.38607
		},
		"current_speed": 0.0,
		"altitude": 0.0,
		"system_usage": 0.0
	});

	const sendLandOrder = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/putDroneOrder?drone_id=` + String(
					currentSelectDroneId.value), // 手动拼接参数
				method: 'PUT',
				data: ["land",Date.now()],
				header: {
					'Content-Type': 'application/json'
				}
			});
			if (response.statusCode === 200) {
				isSendTakeOffOrder.value = false;
				uni.showToast({
					title: '降落发送成功',
					icon: 'success'
				});
			} else {
				console.error('降落发送失败，状态码:', response.statusCode);
				uni.showToast({
					title: '降落发送失败',
					icon: 'error'
				});
			}
		} catch (error) {
			// 更详细的错误捕获
			console.error('请求异常:', {
				message: error.errMsg || error.message,
				code: error.errno || error.code,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	const sendTakeOffOrder = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/putDroneOrder?drone_id=` + String(
					currentSelectDroneId.value), // 手动拼接参数
				method: 'PUT',
				data: ["take_off",Date.now()],
				header: {
					'Content-Type': 'application/json'
				}
			});
			if (response.statusCode === 200) {
				isSendTakeOffOrder.value = true;
				uni.showToast({
					title: '起飞发送成功',
					icon: 'success'
				});
			} else {
				console.error('起飞发送失败，状态码:', response.statusCode);
				uni.showToast({
					title: '起飞发送失败',
					icon: 'error'
				});
			}
		} catch (error) {
			// 更详细的错误捕获
			console.error('请求异常:', {
				message: error.errMsg || error.message,
				code: error.errno || error.code,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	// 获取路线名与路线id
	const fetchActiveRouteNameAndIdList = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/getActiveRoutes`,
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				}
			});

			if (response.statusCode === 200) {
				routeNameAndId.value = response.data.data;
			} else {
				console.error('请求失败，状态码:', response.statusCode);
				uni.showToast({
					title: `请求失败: ${response.statusCode}`,
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('请求异常:', {
				message: error.errMsg,
				code: error.errno,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	// 获取无人机ID列表
	const fetchDroneIdList = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/monitor/getDroneIdList`,
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				}
			});

			if (response.statusCode === 200) {
				droneIdList.value = response.data.data;
			} else {
				console.error('请求失败，状态码:', response.statusCode);
				uni.showToast({
					title: `请求失败: ${response.statusCode}`,
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('请求异常:', {
				message: error.errMsg,
				code: error.errno,
				stack: error.stack
			});

			uni.showToast({
				title: `请求异常：${error.errMsg}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	const handlecurrentSelectDroneIdChange = (e) => {
		const selectedIndex = e.detail.value;
		currentSelectDroneId.value = droneIdList.value[selectedIndex];
		hasChooseDrone.value = true;
	};
const telemetry_GPS_to_Gcj02=ref([]);

	//获取无人机遥测数据
	const fetchTelemetryData = async () => {
		if (currentSelectDroneId.value != null) {
			try {
				const response = await uni.request({
					url: getApp().globalData.rootUrl + `/monitor/getTelemetry?drone_id=` + String(
						currentSelectDroneId.value),
					method: 'GET',
					header: {
						'Content-Type': 'application/json'
					}
				});

				if (response.statusCode === 200) {
					telemetryData.value = response.data.data;
					telemetry_GPS_to_Gcj02.value=wgs84ToGcj02(telemetryData.value.current_gps.longitude,telemetryData.value.current_gps.latitude);
					markers.value = [];
					// mapKey.value++;
					const newMarker = {
						id: markers.value.length + 1,
						latitude: telemetry_GPS_to_Gcj02.value[1],
						longitude: telemetry_GPS_to_Gcj02.value[0],
						iconPath: '/static/icons/drone_blue.png',
						title: "无人机当前坐标",
						width: 15,
						height: 15
					};
					markers.value.push(newMarker);
				} else {
					console.error('请求失败，状态码:', response.statusCode);
					uni.showToast({
						title: `请求失败: ${response.statusCode}`,
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('请求异常:', {
					message: error.errMsg,
					code: error.errno,
					stack: error.stack
				});

				uni.showToast({
					title: `请求异常：${error.errMsg}`,
					icon: 'none',
					duration: 3000
				});
			}
		}
	};

	const mapKey = ref(0);

	const currentAction = ref(null);

	const handleActionClick = async (action) => {
		if(currentSelectDroneId.value == null){
			uni.showToast({
				title: `请选择无人机`,
				icon: 'none'
			});
			return;
		}
		currentAction.value = action;
		console.log(`切换到 ${action} 模式`);
		if(action=="pause"){
			sendSpeedCommand(currentSelectDroneId.value,0.0,0.0,0.0);
		}else{
			checkAndExecuteAction();
		}
	};

	// 新增页面可见性状态
	const isPageVisible = ref(true);
	
	
	// 监听页面显示/隐藏事件
	onShow(() => {
		isPageVisible.value = true;
	});
	
	onHide(() => {
		isPageVisible.value = false;
	});
	
	// 新增检查执行函数
	const checkAndExecuteAction = async () => {
		if (!isPageVisible.value) return;
		if (!currentSelectDroneId.value) return;
		if (currentAction.value === 'pause') return;
	
		switch(currentAction.value) {
			case 'left':
				sendSpeedCommand(currentSelectDroneId.value, 1000, 0.0, 200);
				break;
			case 'right':
				sendSpeedCommand(currentSelectDroneId.value, 1000, 0.0, -200);
				break;
			case 'u_turn_left':
				sendSpeedCommand(currentSelectDroneId.value, 0.0, 0.0, 200);
				break;
			case 'u_turn_right':
				sendSpeedCommand(currentSelectDroneId.value, 0.0, 0.0, -200);
				break;
			case 'backward':
				sendSpeedCommand(currentSelectDroneId.value, -1000, 0.0, 0.0);
				break;
			case 'forward':
				sendSpeedCommand(currentSelectDroneId.value, 1000, 0.0, 0.0);
				break;
		}
	};

	const isRecording = ref(false);


	const isAutoMode = ref(false);

	const handleAutoMode = () => {
		isAutoMode.value = !isAutoMode.value;
		console.log(`自动模式 ${isAutoMode.value ? '开启' : '关闭'}`);
		// 这里添加自动模式切换逻辑
	};


const recordingPoints = ref([]);
const autoRecordInterval = ref(null);

// 修改后的开始录制函数
const startRecording = () => {
  if (!currentSelectDroneId.value) {
    uni.showToast({ title: '请先选择无人机', icon: 'none' });
    return;
  }
  isRecording.value = true;
  recordingPoints.value = []; // 清空之前的记录
  
  // 如果是自动模式，启动定时器
  if (isAutoMode.value) {
    // 立即记录第一个点
    recordCurrentPosition();
    autoRecordInterval.value = setInterval(() => {
      recordCurrentPosition();
    }, 10000);
  }
  console.log("开始录制");
};

// 新增记录当前位置函数
const recordCurrentPosition = () => {
  if (telemetryData.value.current_gps) {
    const point = {
      latitude: telemetryData.value.current_gps.latitude,
      longitude: telemetryData.value.current_gps.longitude,
      timestamp: Date.now()
    };
    recordingPoints.value.push(point);
    uni.showToast({ title: `自动记录点 ${recordingPoints.value.length}`, icon: 'none' });
  }
};

// 修改后的取消录制函数
const handleCancelRecording = () => {
  isRecording.value = false;
  if (autoRecordInterval.value) {
    clearInterval(autoRecordInterval.value);
    autoRecordInterval.value = null;
  }
  recordingPoints.value = [];
  uni.showToast({ title: '已取消录制', icon: 'none' });
};

// 修改后的新增点函数
const handleAdd = () => {
  if (isRecording.value && !isAutoMode.value) {
    if (telemetryData.value.current_gps) {
      const newPoint = {
        latitude: telemetryData.value.current_gps.latitude,
        longitude: telemetryData.value.current_gps.longitude,
        timestamp: Date.now()
      };
      recordingPoints.value.push(newPoint);
      uni.showToast({ title: `手动记录点 ${recordingPoints.value.length}`, icon: 'none' });
    }
  } else {
    uni.showToast({ title: '请先开始手动录制', icon: 'none' });
  }
};

// 修改后的删除函数
const handleDelete = () => {
  if (isRecording.value && !isAutoMode.value) {
    if (recordingPoints.value.length > 0) {
      recordingPoints.value.pop();
      uni.showToast({ title: `已删除点，剩余${recordingPoints.value.length}个`, icon: 'none' });
    }
  }
};

const handleSaveRecording = async () => {
  if (recordingPoints.value.length === 0) {
    uni.showToast({ title: '没有记录点可保存', icon: 'none' });
    return;
  }

  uni.showModal({
    title: '保存路线',
    content: '请输入路线名称',
    editable: true,
    success: async (res) => {
      if (res.confirm) {
        const routeName = res.content;
        if (!routeName) {
          uni.showToast({ title: '路线名称不能为空', icon: 'none' });
          return;
        }
        
        try {
          // 转换坐标格式
          const coordinates = recordingPoints.value.map(point => ({
            latitude: Number(point.latitude.toFixed(6)),
            longitude: Number(point.longitude.toFixed(6))
          }));

          const response = await uni.request({
            url: getApp().globalData.rootUrl + '/routes/createRoute',
            method: 'POST',
            data: {
              routeName: routeName,
              coordinates: JSON.stringify(coordinates),
              isActive: true  // 默认创建后立即激活
            },
            header: { 
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + getApp().globalData.token // 添加认证头
            }
          });

          if (response.statusCode === 200) {
            if(response.data.code === 200) {
              uni.showToast({ title: '路线保存成功', icon: 'success' });
              isRecording.value = false;
              if (autoRecordInterval.value) {
                clearInterval(autoRecordInterval.value);
                autoRecordInterval.value = null;
              }
              recordingPoints.value = [];
            } else {
              uni.showToast({ title: '保存失败：' + response.data.message, icon: 'none' });
			  console.log("保存失败");
            }
          } else {
            uni.showToast({ title: '请求失败：' + response.statusCode, icon: 'none' });
			console.log("请求失败");
          }
        } catch (error) {
          uni.showToast({ title: '请求异常：' + error.errMsg, icon: 'none' });
		  console.log("请求异常");
        }
      }
    }
  });
};

	onMounted(() => {
		fetchDroneIdList();
		fetchActiveRouteNameAndIdList();
		timer.value = setInterval(() => {
			fetchTelemetryData();
			checkAndExecuteAction();
		}, 200);
	});

	onUnmounted(() => {
		if (timer.value) clearInterval(timer.value);
	});
</script>


<style lang="scss" scoped>

</style>